package linear_list.leetcode.easy;

/**
 * @author bruin_du
 * @description 从尾到头打印链表
 * @date 2022/5/10 18:40
 **/
public class offer06_ReversePrint {
    public int[] reversePrint(ListNode head) {
        //遍历两遍，第一遍记录链表的长度，第二遍保存到数组中
//        if(head == null)
//            return new int[0];
//        int length = 0;
//        ListNode pHead = head;
//        while(pHead != null){
//            pHead = pHead.next;
//            length++;
//        }
//        pHead = head;
//        int[] arr = new int[length];
//        for (int i = length - 1; i >= 0; i--) {
//            arr[i] = pHead.val;
//            pHead = pHead.next;
//        }
//        return arr;

        //递归
        return reversePrintRecursion(head,0);
    }

    private int[] reversePrintRecursion(ListNode head, int count) {
        if(head == null)
            return new int[count];
        int[] arr = reversePrintRecursion(head.next,count + 1);
        arr[arr.length - count - 1] = head.val;
        return arr;
    }
}
